<template>
 <div class="container">
     <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="学员姓名：" prop="name">
        <el-input v-model="ruleForm.name" style="width:20%"></el-input>
      </el-form-item>
      <el-form-item label="学员类型：" prop="region">
        <el-select v-model="ruleForm.type" disabled="disabled" placeholder="">
          <el-option label="正式学员" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学员性别：" prop="sex">
        <el-select v-model="ruleForm.sex" placeholder="请选择学员性别">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学员生日：" prop="birthday">
          <el-date-picker
              v-model="ruleForm.birthday"
              type="date"
              placeholder="请选择学员生日">
          </el-date-picker>
      </el-form-item>
      <el-form-item label="手机号码：" prop="phone">
        <el-input v-model="ruleForm.phone" style="width:20%"></el-input> 
      </el-form-item>
      <el-form-item label="所购商品：" prop="goodsId">
        <el-select v-model="ruleForm.goodsId" @change="selectAjaxOne" placeholder="请选择所购商品">
          <el-option
              v-for="(val,index) in goodsIdArr"
              :key="index"
              :label="`${val.name}- - -${val.classType}`"
              :value="val.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品价格：" prop="">
        <el-input disabled v-model="selectPrice" style="width:14.5%"></el-input>
        <span></span>
      </el-form-item>
      <el-form-item label="材料费：" prop="">
        <el-input disabled v-model="materialPrice" style="width:14.5%"></el-input>
        <span></span>
      </el-form-item>
      <el-form-item label="折扣：" prop="">
        <el-input v-model="ruleForm.saleRatio" style="width:10%"></el-input>
        <span>({{this.masterData.operateRatio}} ~ 1)</span>
      </el-form-item>
      <el-form-item label="合计金额：" v-model="ruleForm.orderAmount">
        <span>折后价：</span>
        <span style="color:red">￥{{this.getDisountPrice}}</span>
      </el-form-item>
      <el-form-item label="微信：" prop="">
        <el-input v-model="ruleForm.wxNickName" style="width:20%"></el-input>
      </el-form-item>
      <el-form-item label="客户来源：" prop="">
        <el-input v-model="ruleForm.customerSource" style="width:20%"></el-input>
      </el-form-item>
      <el-form-item label="课程顾问：" prop="">
        <el-select v-model="ruleForm.organizationUserId" placeholder="请选择课程顾问">
          <el-option
              v-for="item in organizationArr"
              :key="item.organizationUserId"
              :label="item.name"
              :value="item.organizationUserId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      </el-form-item>
    </el-form>
 </div>
</template>

<script>
export default {
  data() {
    return {
      selectPrice:0,
      materialPrice:0,
			matePrice:0,
      masterData: [],
      minRatio:'',
      maxRatio:'',
      // 课程顾问数据
      organizationArr: {
        organizationUserId: "",
        name: ""
      },
			isrule:true, //验证数据类型是否正确  正确时才能发送请求
      TwoDiscount:"",
      // 商品数据
      goodsIdArr: [],
      ruleForm: {
        name: "", //名字
        type: "1", //类型
        sex: "", //性别
        birthday: "", //学员生日
        phone: "", //手机号
        goodsId: "", //商品id
        saleRatio: 1, //折扣
        orderAmount: "", //合计金额
        wxNickName: "", //微信
        customerSource: "", //客户来源
        organizationUserId: "", //客户顾问id
      },
      rules: {
        name: [{ required: true, message: "请输入学员姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请选择学员性别", trigger: "blur" }],
        birthday: [
          { required: true, message: "请选择学员生日", trigger: "blur" }
        ],
        wxNickName: [
          { required: true, message: "请输入微信用户名", trigger: "blur" }
        ],
        goodsId: [
          { required: true, message: "请选择所购商品", trigger: "change" }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[34578]\d{9}$/, message: "请输入正确的手机号" }
        ],
        customerSource: [
          { required: true, message: "请输入客户来源", trigger: "blur" },
        ],
        organizationUserId: [
          { required: true, message: "请选择课程顾问", trigger: "blur" },
        ],
        saleRatio: [
          { required: true, message: "请输入折扣价格", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.selectChanelAjax();
    this.goodsIdArrAjax();
    this.goodsIdAjaxOne();
    this.getDatas();
		if(this.$route.query.studentId){
      var studentId = this.$route.query.studentId
      console.log(studentId);
			this.getData(studentId);
		}
  },
  mounted(){
    
  },
  computed: {
      getDisountPrice: function () {
      this.Discountprice = (this.selectPrice * this.ruleForm.saleRatio+this.matePrice).toFixed(2)
        return this.Discountprice
      }
    },
  methods: {
    //获取机构信息
    getDatas() {
      var that = this;
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.url = "/api/user/xzs/organization.info.get";
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          organizationId: organizationId
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=  encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          }
        ],
      }).then(res => {
          this.masterData = res.data.data;
          this.maxRatio = res.data.data.maxRatio
          this.minRatio = res.data.data.minRatio
          this.form = Object.assign({},this.form,res.data.data)
        })
        .catch(err => {
        });
    },
		getData(studentId){
			let that = this;
			var url = "/api/user/xzs/student.info.get";
			var data={};
			data.studentId = studentId;
			this.axios.get(url, {
			　　params: { 'studentId': studentId }
			}).then(function (res) {
        console.log(res);
				if(res.data.errorCode == 0){  
					that.ruleForm = res.data.data;
					that.ruleForm.type = String(that.ruleForm.type);
					that.ruleForm.sex = String(that.ruleForm.sex);
					if(that.ruleForm.goodsId){
						that.selectAjaxOne(that.ruleForm.goodsId);
					}
				}
			}).catch(function (error) {

			}); 
		},
    submitForm(formName) {
      var that = this;
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.url = "/api/user/xzs/student.info.save";
        Date.prototype.format = function(formatStr){
            var str = formatStr;
            str=str.replace(/yyyy|YYYY/,this.getFullYear());
            str=str.replace(/MM/,(this.getMonth()+1)>9?(this.getMonth()+1).toString():'0' + (this.getMonth()+1));
            str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
            return str;
        }
				if(typeof(that.ruleForm.birthday) =="number"){
					that.ruleForm.birthday = new Date(that.ruleForm.birthday / 10000);
				}
        // that.ruleForm.birthday=that.ruleForm.birthday.format("yyyy-MM-dd")
      this.$refs[formName].validate(valid => {
				var data={
					name:that.ruleForm.name,
					type:parseInt(that.ruleForm.type),
					sex: parseInt(that.ruleForm.sex),
					birthday:that.ruleForm.birthday,
					phone:that.ruleForm.phone,
					goodsId:that.ruleForm.goodsId,
					saleRatio: parseFloat(that.ruleForm.saleRatio),
					orderAmount: that.ruleForm.orderAmount,
					wxNickName:that.ruleForm.wxNickName,
					customerSource:that.ruleForm.customerSource,  
					organizationUserId:that.ruleForm.organizationUserId,
          organizationId:organizationId,
				}
				if(this.ruleForm.id){
					data.studentId = this.ruleForm.id;
				}
				if ( parseFloat(this.ruleForm.saleRatio) < this.masterData.operateRatio || parseFloat(this.ruleForm.saleRatio) > 1) {
          this.$message({
						showClose: true,
						message: "折扣价格只能设置在"+this.masterData.operateRatio+ '-' + 1 +"之间",
						type: "warning"
					});
          this.isrule = false;
				}else{
					this.isrule = true;
        }
        console.log(this.isrule);
        if (this.isrule) {
          this.$axios({
            url:this.url,
            method:'post',
            data:this.$qs.stringify(data),
          }).then(res =>{
            if(res.data.errorCode == 0){
							var title = "添加成功";
							if(this.ruleForm.id){
                title = "更新成功"
							}
							this.$message({
								showClose: true,
								message: title,
								type: "success"
							});
							this.$router.push("/Formalcadets");
						}
            if(res.data.errorCode == 500){
                this.$message({
                  showClose: true,
                  message: "服务器错误",
                  type: "warning"
                });
              }
            }).catch(err =>{
          })
        } else {
          return false;
        }
      });
    },
    saleRatioJudge() {},
    selectAjaxOne(id) {
      var obj = {};
      obj = this.goodsIdArr.find((item)=>{
        return item.id === id
      });
      this.selectPrice = obj.goodsPrice
      this.materialPrice = obj.materialPrice
      this.matePrice = obj.materialPrice;
      this.classType = obj.classType
    },
    //课程顾问数据
    selectChanelAjax() {
      let organizationId = JSON.parse(localStorage.getItem("organizationIds"))[0];
      this.url = "/api/user/xzs/organizationUser.list.get";
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          organizationId: organizationId
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          }
        ]
      }).then(res => {
          this.organizationArr = res.data.data;
        },err => {
          console.log(err);
        }
      );
    },
    // 商品列表获取单条数据
    goodsIdAjaxOne(type, id) {
      this.url = "/api/goods/xzs/goods.info.get";
      this.$axios({
        url: this.url,
        method: "post",
        data: {
          goodsId: "1"
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
            }
            return ret;
          }
        ]
      }).then(res => {
        },err => {
          console.log(err);
        }
      );
    },
    //商品列表数据
    goodsIdArrAjax() {
      this.url = "/api/goods/xzs/goods.list.get";
      this.$axios.post(this.url, {}).then(res => {
        this.goodsIdArr = res.data.data;
        this.goodsIdArr.forEach(element => {
          if(element.classType == 1){
            element.classType = "大班"
          }else if(element.classType == 2){
            element.classType = "中班"
          }else if(element.classType == 3){
            element.classType = "小班"
          }else if(element.classType == 4){
            element.classType = "通用"
          }
        });
      });
    }
  },  
};
</script>
<style>
</style>